﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Threading;

namespace Snake.Model
{
    class Client
    {

        private NetworkStream clientStream;
        private Thread Listen;
        public Client()
        {
            //déclaration client tcp
            TcpClient client = new TcpClient();

            //mise en place des paramêtres.
            IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 3000);


            //connexion serveur
            client.Connect(serverEndPoint);

            //configure network
            this.clientStream = client.GetStream();
            
           

            
            //vide les donnée
            clientStream.Flush();
        
            //utilisait un thread pour recevoir les donnée
        }

        public void Envoi(string NamePlayeur)
        {
             //permet l'envoi
            ASCIIEncoding encoder = new ASCIIEncoding();
            //buffer pour envoi
            byte[] buffer = encoder.GetBytes(NamePlayeur);
            //System.Windows.Forms.MessageBox.Show("Nom de mon adversaire "+NamePlayeur);  
            //envoie information
            clientStream.Write(buffer, 0, buffer.Length);

        }

        public void Reception()
        {
            this.Listen = new Thread(new ThreadStart(Receptions));
            this.Listen.Start();
            byte[] message = new byte[4096];
            clientStream.Read(message, 0, 4096);
            ASCIIEncoding encoder = new ASCIIEncoding();
            int bytesRead = 0;
            String NameOtherPlayer = encoder.GetString(message, 0, bytesRead);
            System.Windows.Forms.MessageBox.Show("Client Nom de mon adversaire " + NameOtherPlayer);  
            
        }

        private void Receptions()
        {
            while (true)
            {
                byte[] message = new byte[4096];
                clientStream.Read(message, 0, 4096);
                ASCIIEncoding encoder = new ASCIIEncoding();
                int bytesRead = 0;
                String NameOtherPlayer = encoder.GetString(message, 0, bytesRead);
                System.Windows.Forms.MessageBox.Show("Client Nom de mon adversaire " + NameOtherPlayer);
            }

        }

        public void Endclient()
        {
            this.Listen.Abort();

        }
    }
}
